package com.hhb.controller;


import com.hhb.constant.BaseController;
import com.hhb.constant.Result;
import com.hhb.service.IPermisionService;
import jakarta.annotation.Resource;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController extends BaseController {
    @Resource
    private IPermisionService permisionService;
    @PostMapping("/login")
    public Result doLogin(@RequestBody Map<String,String> map){
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken(map.get("username"),map.get("password"));
            try {
                subject.login(token);
            } catch (AuthenticationException e) {
                e.printStackTrace();
                return new Result(500,"登录失败 ");
            }

        }
        HashMap<String, String> map1 = new HashMap<>();
        map1.put("token",subject.getPrincipal().toString());
        return this.toDataResult(map1);
    }
    @GetMapping("/info")
    public Result getInfo(String token){
//        String account = SecurityUtils.getSubject().getPrincipal().toString();
        HashMap<String, Object> mp = new HashMap<>();
        mp.put("roles","account");
        mp.put("name","lan");
        mp.put("avatar","https://tse1-mm.cn.bing.net/th/id/OIP-C.pL9aeO50HMujMSzGcOPhKwAAAA?w=220&h=220&c=7&r=0&o=5&dpr=1.3&pid=1.7");
        List<String> perms = permisionService.listPerms(token);
        mp.put("permission",perms);
        return this.toDataResult(mp);
    }
    @RequestMapping("/toLogin")
    public Result toLogin(){
        return new Result(50008,"登录失败");
    }
    @PostMapping("/logout")
    public Result logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new Result(200,"注销成功");
    }

}
